#include "test.h"

static int count = 0;

xthread_mutex_t mutex;

static void *thread_changer(void *arg)
{
    int old;
    while (1) {
        xthread_mutex_lock(&mutex);
        count++;
        old = count;
        printf("thread: %d, count=%d\n", xthread_self(), count);
        xthread_sleep(1);
        if (old != count)
            printf("thread: %d, count=%d -> old=%d are different!\n", xthread_self(), count, old);
        xthread_mutex_unlock(&mutex);
    }
}

static void *thread_reader(void *arg)
{
    while (1) {
        xthread_sleep(1);
        printf("thread: %d, count=%d\n", xthread_self(), count);
    }
}

int test_mutex(int argc, char *argv[])
{
    xthread_mutex_init(&mutex);
    count = 0;
    xthread_t tid0;
    if (xthread_create(&tid0, NULL, thread_changer, "a") < 0)
            printf("xthread create failed!\n");
    xthread_t tid1;
    if (xthread_create(&tid1, NULL, thread_reader, "b") < 0)
            printf("xthread create failed!\n");
    xthread_t tid2;
    if (xthread_create(&tid2, NULL, thread_changer, "c") < 0)
            printf("xthread create failed!\n");
    
    void *status;
    xthread_join(tid0, &status);
    printf("thread %x exit with %x\n", tid0, status);
    return 0;
}
